# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2005-2006 CamptoCamp
# Copyright (c) 2006-2010 OpenERP S.A
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import os, time
from datetime import datetime, timedelta
from openerp.osv import osv, fields
from openerp.tools.translate import _
from openerp.report import report_sxw
import locale
from mx import DateTime as dt
from PIL.TiffImagePlugin import DATE_TIME
from mx.Tools.mxTools.mxTools import sign
from array import array
locale.setlocale(locale.LC_ALL, '')
from openerp.tools import float_round, float_is_zero, float_compare

class inventory_valuation_report_pdf(report_sxw.rml_parse):
    _name = 'inventory.valuation.report.pdf'
    
    
    def _search_data(self, cr, uid, ids, data_obj, val_data, filter_selection, default_from, default_to, input_from, input_to, selection_ids, context=None):
        #Out Default Value
        data_header = ''
        data_ids = []
        #Declaration

        if context is None:
            context = {}
            
#         special_case = 'special_case' in context and context['special_case'] or False  
        if filter_selection == 'all_vall':
            data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'def':
            data_found = False 
            if default_from and data_obj.browse(cr, uid, default_from) and data_obj.browse(cr, uid, default_from).name:
                default_from_header = data_obj.browse(cr, uid, default_from).name
                data_found = True
                val_data.append(('name', '>=', default_from_header)) 
            if default_to and data_obj.browse(cr, uid, default_to) and data_obj.browse(cr, uid, default_to).name:
                default_to_header = data_obj.browse(cr, uid, default_to).name
                data_found = True
                val_data.append(('name', '<=', default_to_header)) 
            if data_found:
                data_header = '"' + default_from_header + '" - "' + default_to_header + '"'
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC') 
        if filter_selection == 'input':
            data_found = False
            if input_from:     
                data_ids_from = data_obj.search(cr, uid, [('name','=ilike',input_from + '%')], order="name", limit=1)
                if data_ids_from:
                    input_from_name = data_obj.browse(cr, uid, data_ids_from[0]).name
  
                    data_found = True
                    val_data.append(('name', '>=', input_from_name))
            if input_to:    
                data_ids_to = data_obj.search(cr, uid, [('name','=ilike', input_to + '%')], order="name desc", limit=1)
                if data_ids_to:
                    input_to_name = data_obj.browse(cr, uid, data_ids_to[0]).name
                    data_found = True
                    val_data.append(('name', '<=', input_to_name))
            data_header = '"' + input_from + '" - "' + input_to + '"'
            if data_found:
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'selection':
            if selection_ids:
                sel_ids = '' 
                for sel in  data_obj.browse(cr, uid, selection_ids):
                    sel_ids += ('"%s",')%(sel.name,) 
                data_header = '[' + sel_ids +']'
                data_ids =selection_ids
                
                data_ids = data_ids
                data_header = data_header
                
        return data_header, data_ids

    
    def set_context(self, objects, data, ids, context=None):
        new_ids = ids
        if context is None:
            context = {}
        
        stock_location_obj     = self.pool.get('stock.location')
        product_product_obj = self.pool.get('product.product')
        product_template_obj = self.pool.get('product.template')
          
        self.sortby_ids = data['form']['sortby_ids'] or False
        self.location_filter_selection = data['form']['location_filter_selection'] or False
#         self.product_type_filter_selection = data['form']['product_type_filter_selection'] or False
        self.product_filter_selection = data['form']['product_filter_selection'] or False
         
        self.output_product_header, self.products_ids = self._search_data(self.cr, self.uid, ids, product_product_obj,
                                                                                      [],
                                                                                      data['form']['product_filter_selection'],
                                                                                      data['form']['product_def_from'] and data['form']['product_def_from'][0] or False,
                                                                                      data['form']['product_def_to'] and data['form']['product_def_to'][0] or False,
                                                                                      data['form']['product_input_from'] or False,
                                                                                      data['form']['product_input_to'] or False,
                                                                                      data['form']['product_ids'] or False,
                                                                                      context=context)
        
        self.output_location_header, self.location_ids = self._search_data(self.cr, self.uid, ids, stock_location_obj,
                                                                                      [],
                                                                                      data['form']['location_filter_selection'],
                                                                                      data['form']['location_def_from'] and data['form']['location_def_from'][0] or False,
                                                                                      data['form']['location_def_to'] and data['form']['location_def_to'][0] or False,
                                                                                      data['form']['location_input_from'] or False,
                                                                                      data['form']['location_input_to'] or False,
                                                                                      data['form']['location_ids'] or False,
                                                                                      context=context)
         
        
          
        return super(inventory_valuation_report_pdf, self).set_context(objects, data, new_ids)

    def __init__(self, cr, uid, name, context=None):
        super(inventory_valuation_report_pdf, self).__init__(cr, uid, name, context=context)
        self.report_total = 0.00
        self.invt_by_cur = {}
        self.uid=uid
        self.localcontext.update({
            'time': time,
            'locale': locale,
            'get_lines': self._get_lines,
            'get_header_title': self._get_header, 
            'get_printed_date' : self._get_printed_date,  
            'get_decimal_accuracy_account': self._get_decimal_accuracy_account,
            'get_decimal_accuracy_product_price': self._get_decimal_accuracy_product_price,
            'get_decimal_accuracy_uom': self._get_decimal_accuracy_uom,
            'get_printed_by': self._get_printed_by,
            'get_output_product_header': self._get_output_product_header,
            'get_output_location_header': self._get_output_location_header,  
            'get_output_sortby_header': self._get_output_sortby_header,
            'get_report_total': self._get_report_total
 
            })
 
    def _get_report_total(self):
        return self.report_total
    
    def _get_printed_date(self):
        header = ''
        user_obj = self.pool.get('res.users')
        user_ids = user_obj.search(self.cr, self.uid, [('id','=',self.uid)])
        if user_ids :
            tz = user_obj.browse(self.cr, self.uid, user_ids[0])
            tz_name = tz.tz
        os.environ['TZ'] = tz_name #set time zone secara otomatis tidak hard code
        time.tzset()
        header = 'Printed date : ' + time.strftime("%Y/%m/%d") + '  Time : '+ time.strftime("%H:%M:%S")
         
        return header
    
    def _get_printed_by(self):
        header =''
        user_obj = self.pool.get('res.users')
        user_ids = user_obj.search(self.cr, self.uid, [('id','=',self.uid)])
        if user_ids :
            user_id = user_obj.browse(self.cr, self.uid, user_ids[0])
            user_name = user_id.name
        
        header = 'Printed by : ' +user_name
        
        return header
    
    def _get_output_product_header(self):
        header = ''
        if self.output_product_header:
            header = 'Product : ' + self.output_product_header
         
        return header
    
    def _get_output_location_header(self):
        header = 'Location : All Internal Location'
        if self.output_location_header:
            header = 'Location : ' + self.output_location_header
         
        return header
      
      
    def _get_output_sortby_header(self):
        header = output_sortby_header = ''
        result = []
        inventory_valuation_sortby_ids = ""
        if self.sortby_ids:
            inventory_valuation_sortby_ids = self.pool.get('inventory.valuation.sortby').search(self.cr, self.uid, [('id', 'in', self.sortby_ids)], order='seq desc')
        
        if inventory_valuation_sortby_ids:
            for item in self.pool.get('inventory.valuation.sortby').browse(self.cr, self.uid, inventory_valuation_sortby_ids):
                result.append({
                        'seq' : item['seq'],
                        'sort_by' : item['sort_by'],
                        })
            result = result and sorted(result, key=lambda val_res: val_res['seq']) or []               
            
            for rs in result:
                sort_name = ''
                if rs['sort_by'] == 'location_name':
                    sort_name = 'Location'
                elif rs['sort_by'] == 'product_name':
                    sort_name = 'Product' 
                output_sortby_header += ('"%s",')%(sort_name,)
            header = 'Sort By : ' + output_sortby_header

        return header
    
    def _get_decimal_accuracy_account(self):
        dp = 2
        dp_obj = self.pool.get('decimal.precision')
        dp_ids = dp_obj.search(self.cr, self.uid, [('name','=','Account')])
        if dp_ids :
            dp_id = dp_obj.browse(self.cr, self.uid, dp_ids[0])
            dp = dp_id.digits
        return dp
    
    def _get_decimal_accuracy_product_price(self):
        dp = 5
        dp_obj = self.pool.get('decimal.precision')
        dp_ids = dp_obj.search(self.cr, self.uid, [('name','=','Product Price')])
        if dp_ids :
            dp_id = dp_obj.browse(self.cr, self.uid, dp_ids[0])
            dp = dp_id.digits
        return dp
    
    def _get_decimal_accuracy_uom(self):
        dp = 3
        dp_obj = self.pool.get('decimal.precision')
        dp_ids = dp_obj.search(self.cr, self.uid, [('name','=','Product Unit of Measure')])
        if dp_ids :
            dp_id = dp_obj.browse(self.cr, self.uid, dp_ids[0])
            dp = dp_id.digits
        return dp   
     
    def _get_header(self):
        header = 'Inventory Valuation Report'
        return header
      
    def _get_lines(self):
        cr              = self.cr
        uid             = self.uid
        
        user_obj = self.pool.get('res.users')
        product_product_obj = self.pool.get('product.product')
        product_template_obj = self.pool.get('product.template')
        inv_valuation_sortby_obj = self.pool.get('inventory.valuation.sortby')
        val_product = ''
        results1        = []
#         val_part = self.val_part 
          
        product_ids = self.products_ids
        location_ids = self.location_ids
        
        if product_ids: 
            product_ids_qry = (product_ids and ((len(product_ids) == 1 and " and sq.product_id = " + str(product_ids[0]) + " ") or " and sq.product_id in " + str(tuple(product_ids)) + " ")) or " and sq.product_id in (0) "
            val_product += product_ids_qry
        
        if location_ids:
            location_ids_qry = (location_ids and ((len(location_ids) == 1 and " and sq.location_id = " + str(location_ids[0]) + " ") or " and sq.location_id in " + str(tuple(location_ids)) + " ")) or " and sq.location_id in (0) "
            val_product += location_ids_qry
          
        inventory_valuation_sortby_ids = []
        if self.sortby_ids:
            inventory_valuation_sortby_ids = inv_valuation_sortby_obj.search(cr, uid, [('id', 'in', self.sortby_ids)], order='seq desc')
        
#         product_product_ids=product_product_obj.search(cr, uid,val_product)
#         get home currency
        home_currency = user_obj.browse(cr, uid, uid).company_id.currency_id.name
        total = 0
        cr.execute("select pt.id as product_templ_id, pt.name as product, " \
                    "sl.name as location, coalesce(sum(qty),0) as qty, pu.name as uom  "\
                    " from stock_quant sq "\
                    "left join product_product pp on pp.id = sq.product_id "\
                    "left join product_template pt on pt.id = pp.product_tmpl_id "\
                    "left join stock_location sl on sq.location_id = sl.id "\
                    "left join product_uom pu on pu.id = pt.uom_id "\
                    "where " \
                    " sl.usage = 'internal' " \
                    + val_product + \
                    " group by pt.name, sl.name, pu.name,pt.id  order by pt.name, sl.name")
                
        qry3 = cr.dictfetchall()
        if qry3:
            for t in qry3:
                price = product_template_obj.browse(cr, uid, t['product_templ_id']).standard_price
                total += t['qty'] * price
                results1.append({
                    'product_name' : t['product'],        
                    'qty_available' : t['qty'],
                    'location_name' : t['location'],
                    'price' : price,
                    'currency' : home_currency,
                    'sub_total' : t['qty'] * price,
                    'uom' : t['uom'],
                      
                })
            self.report_total = total
        if inventory_valuation_sortby_ids:
            for valuation_sortby in inv_valuation_sortby_obj.browse(cr, uid, inventory_valuation_sortby_ids):
                results1 = results1 and sorted(results1, key=lambda val_res: val_res[valuation_sortby.sort_by]) or []
        else:
            results1 = results1 and sorted(results1, key=lambda val_res: val_res['location_name']) or [] 
            results1 = results1 and sorted(results1, key=lambda val_res: val_res['product_name']) or [] 
                      
        return results1  
    
    
report_sxw.report_sxw('report.inventory.valuation.report.pdf', 'stock.picking',
'addons/batam_fast_module/stock/report/report/inventory_valuation_report_pdf.rml', parser=inventory_valuation_report_pdf, header=False)
   
         
        
